Ext.define('Era.controller.Event',{
    extend: 'Ext.app.Controller',
    models: ['Event'],
    stores: ['Events'],
    views: ['EventsGrid','Viewport','EventForm','IconField','MainMenu','FinishMenu'],
 
    refs: [
        {
            ref: 'viewport',
            selector: 'viewport'
        },
        {
            ref: 'eventsgrid',
            selector: 'eventsgrid'
        },
        {
            ref: 'eventform',
            selector: 'eventform'
        },
        {
            ref: 'iconfield',
            selector: 'iconfield'
        }
    ],
 
    init: function() {
        this.control({
            'button[action=new_event]': {
                click: this.onShowNewEventForm
            },
            'button[action=manage_events]': {
                click: this.onShowEventsList
            },
            'button[action=hide_form]': {
                click: this.onHideEventForm
            },
            'eventsgrid': { 
                selectionchange: this.onShowEditEventForm
            },        
            'eventform > submit_event': {
                submitform: this.onSubmitForm
            },
            'iconfield': {
                render: this.onIconRender
            }
        });
    },
    
    onSubmitEvent: function(event) {
        
        
        
        
        
        
        
        
        var store = this.getStore('Events');
       
        if (event.phantom != null && event.phantom == true) {
            //save new event in db
            store.add(event);
        } else {  
            //update event in db
            store.update(event);
        } 
        
    },
    
    onShowNewEventForm: function() {
        
        //get the form from the viewport
        var form = this.getViewport().eventForm;
        var record = new Era.model.Event();
             
        //bind event to the form
        form.down('form').getForm().loadRecord(record);
        form.show();   
        
    },
    
    onShowEditEventForm: function(sel,record) {
        
        //get the form from the viewport
        var form = this.getViewport().eventForm;
        record = record[0];
        
        //bind event to the form
        form.down('form').getForm().loadRecord(record);
        form.show();  
        
        //reset the grid selection
        //this.getEventsgrid().getSelectionModel().deselectAll();
    },
 
    onShowFinishForm: function(record) {
        console.log(record);
        Ext.Msg.alert('finish event placeholder');
        
        Ext.create('Era.view.FinishMenu').show();
        
    },
    
    onShowList: function() {
        this.getViewport().eventsList.show();
    },
    
    onSelectIcon: function() {
        Ext.Msg.alert("choose icon");
    },
    
    onIconRender: function() {
        this.getIconfield().getEl().on('click',function() {
            alert('here');
        });
    },
    
    onShowEventsList: function() {
        this.getViewport().eventsList.show();
    }
    
})
